package cn.wolfcode.trip.base.util;

import cn.wolfcode.trip.base.domain.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Set;

//当做service的父类
public class UserContext {

    public static final String USER_IN_SESSION = "USER_IN_SESSION";

    public static final String EXPERSSION_IN_SESSION = "EXPERSSION_IN_SESSION";

    public static HttpSession getSession() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest().getSession();
    }

    //将用户信息共享到作用的代码抽取出来
    public static void setCurrentUser(User user) {
        if (user == null) {
            getSession().invalidate();
        } else {
            getSession().setAttribute(USER_IN_SESSION, user);
        }
    }

    //将获取当前作用域用户信息的代码抽离
    public static User getCurrentUser() {
        return (User) getSession().getAttribute(USER_IN_SESSION);
    }

    //将获取当前作用域权限表达式的代码抽离
    public static Set<String> getCurrentExperssion() {
        return (Set<String>) getSession().getAttribute(EXPERSSION_IN_SESSION);
    }

}
